<?php

namespace api\modules\common\models;

use common\models\Status;
use common\models\user\UserUnusualLog;
use Yii;
use yii\base\Exception;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;

/**
 * Class User
 * @package api\modules\v1\models
 */
//class User extends Common implements IdentityInterface
class User extends \common\models\user\User implements IdentityInterface
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'register_time',
                'updatedAtAttribute' => 'update_time',
                'value' => date('Y-m-d H:i:s')
            ]
        ];
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['login_name' => $username, 'status' => Status::COMMON_STATUS_SHOW]);
    }

    /**
     * Finds user by password reset token
     *c
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => Status::COMMON_STATUS_SHOW,
        ]);
    }

    /**
     * 重置密码时  临时TOKEN验证
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    //=====================  覆盖接口方法（5个） 开始 ================================
    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => Status::COMMON_STATUS_SHOW]);
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // 如果token无效的话，
        if(!static::authKeyIsValid($token)) {
            return false;
        }
        return static::findOne(['access_token' => $token, 'status' => Status::COMMON_STATUS_SHOW]);
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->access_token;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    //=====================  覆盖接口方法（5个） 结束 ================================

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * 记住我时，cookie存储的token
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();
        $this->refresh_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 重置密码时，临时token
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 临时token失效
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    public function loginByRefreshToken() {

    }

    public function loginByAccessToken($token, $type = null) {
        /* @var $class IdentityInterface */
        $identity = static::findIdentityByAccessToken($token, $type);
        if (empty($identity)) {
            throw new Exception('用戶不存在或已被封禁');
        }
    }

    /**
     * 验证用户登录token
     * @param string $refreshToken
     * @return bool
     */
    public static function refreshTokenIsValid($refreshToken = '') {
        if (empty($refreshToken)) {
            return false;
        }

        $timestamp = (int) substr($refreshToken, strripos($refreshToken, '_') + 1);
        $expire = Yii::$app->params['user.RefreshToken'];
        return $timestamp + $expire >= time();
    }

    /**
     * 验证用户登录token
     * @param $token
     *
     * @return bool
     */
    public static function authKeyIsValid($token) {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strripos($token, '_') + 1);
        $expire = Yii::$app->params['user.AccessToken'];
        return $timestamp + $expire >= time();
    }


    /**
     * 检查用于信息
     * @param string $check
     *
     * @return array|null|\yii\db\ActiveRecord
     * @throws Exception
     */
    public function checkUser() {
        $accessToken = Yii::$app->request->headers->get('access-token');
        $userId = $this->getUserId($accessToken);
        if(!$userId) {
            throw new Exception('登录已过期，请重新登录');
        }

        $userInfo = static::getOneByWhere(['id' => $userId]);

        if ($userInfo['status'] == Status::COMMON_RADIO_NO) {
//            UserUnusualLog::checkUserDisable($userId);
            throw new Exception("用户已被禁用");
        }

        return $userInfo;
    }

    /**
     * 检查用于信息 不抛异常
     * @return array|bool|null|\yii\db\ActiveRecord
     */
    public function checkUserNoExp() {
        $accessToken = Yii::$app->request->headers->get('access-token');
        $userId = $this->getUserId($accessToken);
        if(!$userId) {
            return false;
        }

        $userInfo = static::getOneByWhere(['id' => $userId]);

        if ($userInfo['status'] == Status::COMMON_RADIO_NO) {
            return false;
        }


        return $userInfo;
    }

    public function getUserId($token) {
        $user = User::findIdentityByAccessToken($token);
        if($user) {
            return $user->id;
        }
        return false;
    }
}
